package com.xywy.tangandroid.activity;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.base.BaseActivity;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.vollery.GetRequest;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.PostRequest;
import com.xywy.tangandroid.vollery.VolleyManager;

/*
 * 验证码确认
 */
public class ComfrimCodeAct extends BaseActivity {
	private RelativeLayout left_img;
	private TextView middle_title;
	private TextView time_countdown;
	private String phonenum;
	private String accountstr;
	private String password;
	private RelativeLayout binding;
	private EditText input_phone;
	private TextView binding_text;
	private TextView phone_number;
	private int flag;
	private String target;
	private String id;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_confirm_code);
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText(getResources().getString(R.string.confrim));
		time_countdown = (TextView) findViewById(R.id.time_countdown);
		binding = (RelativeLayout) findViewById(R.id.binding);
		input_phone = (EditText) findViewById(R.id.input_phone);
		binding_text = (TextView) findViewById(R.id.binding_text);
		phone_number = (TextView) findViewById(R.id.phone_number);
		flag = getIntent().getIntExtra("flag", -1);

		if (flag == 1) {
			target = getIntent().getStringExtra("target");
			// id = getIntent().getStringExtra("id");//
			binding_text.setText(getResources().getString(
					R.string.set_new_password));
			phone_number.setText(target);
		} else if (flag == 3) {
			target = getIntent().getStringExtra("target");
			//
			binding_text.setText(getResources()
					.getString(R.string.change_phone));
			phone_number.setText(target);
		}
		id = getIntent().getStringExtra("id");

	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		binding.setOnClickListener(this);

		new CountDownTimer(60000, 1000) {

			public void onTick(long millisUntilFinished) {

				time_countdown.setText("接收短信大约需要" + millisUntilFinished / 1000
						+ "秒");
			}

			public void onFinish() {
				ComfrimCodeAct.this.finish();
			}
		}.start();
	}

	@Override
	protected void initData() {
		phonenum = getIntent().getStringExtra("phonenum");
		accountstr = getIntent().getStringExtra("accountstr");
		password = getIntent().getStringExtra("password");
		if (flag == 3) {
			SharedPreferences sp = getSharedPreferences("xywy_tang_user",
					Context.MODE_PRIVATE);
			phonenum = sp.getString("phonenum", "");
			accountstr = sp.getString("accountstr", "");
			// password = "123456";
		}

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			finish();
			break;
		case R.id.binding:
			if (input_phone.getText().toString().trim().length() > 0) {
				if (flag == 1) {
				binding_text.setText("确定");
					SendForgetPasswordCode();
				} else if (flag == 3) {
					SendPhoneRegistCode();
				} else {
					SendPhoneRegistCode();
				}
			} else {
				UIUtil.showToast(context, "未填写哦~");
			}
			break;
		default:
			break;
		}
	}

	private void SendForgetPasswordCode() {
		final String code = input_phone.getText().toString().trim();
		GetRequest<String> getRequest = new GetRequest<String>(Constant.getUrl(
				"sms", "verifyCode")
				+ "&target="
				+ target
				+ "&code="
				+ code
				+ "&type=2&PHPSESSID=" + id, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context,
								context.getString(R.string.network_slow));
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(ComfrimCodeAct.this, waittingDialog);
						try {
							JSONObject jsonObject = new JSONObject(response);
							int code1 = (int) jsonObject.optInt("code");
							String error = (String) jsonObject
									.optString("error");

							if (code1 == 10000) {
								JSONObject data = jsonObject
										.optJSONObject("data");
								if (data != null) {
									String userid = data.optString("userid");
									String phonenumber = data
											.optString("phonenumber");
									User.getIUserInstance(context).setUserid(
											userid);
									User.getIUserInstance(context).setPhonenum(
											phonenumber);
									Intent intent = new Intent(context,
											SetNewPasswordAct.class);
									intent.putExtra("target", target);
									intent.putExtra("code", code);
									startActivity(intent);
									ComfrimCodeAct.this.finish();
								} else {
									Toast.makeText(context, "更改手机号成功！",
											Toast.LENGTH_LONG).show();
									ComfrimCodeAct.this.finish();
								}
							} else {

								UIUtil.showToast(context, error);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				});
		getRequest.setIsParseJson(false);
		executeRequest(getRequest);
	}

	private void SendPhoneRegistCode() {
		final String code = input_phone.getText().toString().trim();
		PostRequest<String> postRequest = new PostRequest<String>(
				Constant.getUrl("kbb", "users") + "&type=registAccount",
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						System.out.println(".....VolleyError" + volleyError);
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context,
								getResources().getString(R.string.network_slow));
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(ComfrimCodeAct.this, waittingDialog);
						JSONObject object;
						try {
							object = new JSONObject(response);

							String error = object.optString("error");
							int state = object.optInt("state");
							if (state == 200) {
								Intent intent = new Intent(context,
										FrameAct.class);
								String userid = object.optString("userid");
								if (userid.length() > 0)
									User.getIUserInstance(context).setUserid(
											userid);

								startActivity(intent);
								ComfrimCodeAct.this.finish();
								// } else if (response.getState() == 504) {
								// UIUtil.showToast(context, "该手机号已被其他账号绑定！");
								// // response.getError()
							} else {
								if (error.length() > 0)
									UIUtil.showToast(context, error); // response.getError()
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				});
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("phonenum", phonenum);
		password = User.getIUserInstance(context).getPassword();
		params.put("password", password);
		params.put("accountstr", accountstr);
		params.put("code", code);
		params.put("sex", "2");
		params.put("height", "0");
		params.put("birthday", System.currentTimeMillis() + "");
		params.put("PHPSESSID", id);
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		executeRequest(postRequest);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(this);
	}
}
